package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.bean.UserInfo;
import com.lily.aidouzixun.fragment.UserCenterFragment;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.MyConstant.IntentForResultCODE;
import com.lily.aidouzixun.util.MyConstant.IntentKey;
import com.lily.aidouzixun.util.MyConstant.ModifyAction;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.io.File;
import java.lang.ref.WeakReference;

/**
 * 用户详情页
 */
public class UserDetailActivity  extends Activity {
    private static final String TAG = "UserDetailActivity";

    private TitleBar mTitleBar;
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条
    private RelativeLayout rlAvatar;    //头像外层布局
    private RelativeLayout rlNickName;    //昵称外层布局
    private RelativeLayout rlAccount;    //账号外层布局
    private LinearLayout llLine;    //线
    private RelativeLayout rlPassword;
    private RelativeLayout rlPhone;    //电话号码外层布局
    private RelativeLayout rlEmail;
    private TextView tvEmail;
    private RelativeLayout rlBirthday;
    private RelativeLayout rlSex;
    private RelativeLayout rlAddress;
    private RelativeLayout rlSelfSign;
    private Button bnQuitLogin;


    private ImageView ivAvatar;
    private TextView tvAccount;
    private TextView tvNickName;
    private TextView tvPhone;

    private String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle;   //返回标题
    private static final String TITLE = "个人信息";
    private MyHandler myHandler;
    private UserInfo mUserinfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.userdetail);
        init();
        findViews();
        setListeners();
    }

    /**
     * 用于
     */
    @Override
    protected void onResume() {
        super.onResume();
        mUserinfo = MyConfig.getUserInfo(mContext);
        if (mUserinfo == null) {//提示登录
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
        } else {
            if (mUserinfo != null) {
                File file = new File(MyConstant.AVATAR_PATH);
                if (file.isFile() && file.length() > 0) {   //如果是刚修改过图片
                    Bitmap bitmap = BitmapFactory.decodeFile(MyConstant.AVATAR_PATH);
                    ivAvatar.setImageBitmap(bitmap);
                } else {
                    if (Validator.isEffective(mUserinfo.getAvatarUrl())) {
                        Glide.with(mContext)
                                .load(mUserinfo.getAvatarUrl())
                                .into(ivAvatar);
                    }
                }
                switch (mUserinfo.getLoginFrom()) {
                    case UserInfo.UserType.USERNAME_PWD:
                        if (Validator.isEffective(mUserinfo.getUsername())) {
                            tvAccount.setText(mUserinfo.getUsername());
                        }
                        break;
                    case UserInfo.UserType.QQ:
                        tvAccount.setText("QQ登录用户");
                        rlPassword.setVisibility(View.GONE);
                        llLine.setVisibility(View.GONE);
                        break;
                    case UserInfo.UserType.PHOME_SMS:
                        tvAccount.setText(mUserinfo.getLoginPhone());
                        rlPassword.setVisibility(View.GONE);
                        llLine.setVisibility(View.GONE);
                        break;
                }

                if (Validator.isEffective(mUserinfo.getNickname())) {
                    tvNickName.setText(mUserinfo.getNickname());
                }
                if (Validator.isEffective(mUserinfo.getEmail())) {
                    tvEmail.setText(mUserinfo.getEmail());
                }
                if (Validator.isEffective(mUserinfo.getPhone())) {
                    tvPhone.setText(mUserinfo.getPhone());
                }
//            String avatarUrl = userInfo.getAvatarUrl();
            }
        }
    }

    /**
     * 初始化参数
     */
    protected void init() {
        this.key += this.hashCode();
        mActivity = UserDetailActivity.this;
        mContext = UserDetailActivity.this;

        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(IntentKey.BACK_TITLE);
        myHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        //清除Glide缓存
        Glide.get(mContext).clearMemory();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(mContext).clearDiskCache();
            }
        }).start();
    }
    /**
     * 找到控件
     */
    protected void findViews() {
        //标题栏
        mTitleBar = (TitleBar) findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);

        rlAvatar = (RelativeLayout) this.findViewById(R.id.rl_avatar);
        ivAvatar = (ImageView) this.findViewById(R.id.iv_avatar);
        rlNickName = (RelativeLayout) this.findViewById(R.id.rl_nickname);
        tvNickName = (TextView) this.findViewById(R.id.tv_nickname);
        rlAccount = (RelativeLayout) this.findViewById(R.id.rl_account);
        tvAccount = (TextView) this.findViewById(R.id.tv_account);
        rlPassword = (RelativeLayout) this.findViewById(R.id.rl_password);
        llLine = (LinearLayout) this.findViewById(R.id.ll_line);
        rlPhone = (RelativeLayout) this.findViewById(R.id.rl_phone);
        tvPhone = (TextView) this.findViewById(R.id.tv_phone);
        rlEmail = (RelativeLayout) this.findViewById(R.id.rl_email);
        tvEmail = (TextView) this.findViewById(R.id.tv_email);
        rlBirthday = (RelativeLayout) this.findViewById(R.id.rl_birthday);
        rlSex = (RelativeLayout) this.findViewById(R.id.rl_sex);
        rlAddress = (RelativeLayout) this.findViewById(R.id.rl_address);
        rlSelfSign = (RelativeLayout) this.findViewById(R.id.rl_selfsign);
        bnQuitLogin = (Button) this.findViewById(R.id.bn_quitlogin);

    }

    /**
     * 设置监听
     */
    protected void setListeners() {
        //头像
        rlAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ShowImageActivity.class);
                File file = new File(MyConstant.AVATAR_PATH);
                if (file.isFile() && file.length() > 0) {   //本地头像有值
                    intent.putExtra(IntentKey.IMAGE_FROM, ShowImageActivity.ImageFrom.FILE_PATH);
                    intent.putExtra(IntentKey.IMAGE_PATH, MyConstant.AVATAR_PATH);
                } else if (Validator.isEffective(mUserinfo.getAvatarUrl())){
                    intent.putExtra(IntentKey.IMAGE_FROM, ShowImageActivity.ImageFrom.URL);
                    intent.putExtra(IntentKey.IMAGE_URL, mUserinfo.getAvatarUrl());
                }
                startActivity(intent);
            }
        });
        //昵称
        rlNickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ModifyUserinfoActivity.class);
                intent.putExtra(IntentKey.ACTION, ModifyAction.MODIFY_NICKNAME);
                intent.putExtra(IntentKey.BACK_TITLE, TITLE);
                intent.putExtra(IntentKey.TITLE, "昵称");
                if (Validator.isEffective(mUserinfo.getNickname())) {
                    intent.putExtra(IntentKey.MODIFY_CONTENT, mUserinfo.getNickname());
                }
                startActivityForResult(intent, IntentForResultCODE.MODIFY_USERINFO_REQUESTCODE);
            }
        });
        //账户
        rlAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                T.longToast(mContext, "账户不可修改");
            }
        });
        //密码
        rlPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ModifyPasswordActivity.class);
                intent.putExtra(IntentKey.BACK_TITLE, TITLE);
                if (Validator.isEffective(mUserinfo.getUsername())) {
                    intent.putExtra(IntentKey.USER_NAME, mUserinfo.getUsername());
                }
                startActivityForResult(intent, IntentForResultCODE.MODIFY_PASSWORD_REQUESTCODE);
            }
        });

        //电话
        rlPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ModifyUserinfoActivity.class);
                intent.putExtra(IntentKey.ACTION, ModifyAction.MODIFY_PHONE);
                intent.putExtra(IntentKey.BACK_TITLE, TITLE);
                if (Validator.isEffective(mUserinfo.getPhone())) {
                    intent.putExtra(IntentKey.MODIFY_CONTENT, mUserinfo.getPhone());
                }
                intent.putExtra(IntentKey.TITLE, "手机号");
                startActivityForResult(intent, IntentForResultCODE.MODIFY_USERINFO_REQUESTCODE);
            }
        });
        //邮箱
        rlEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ModifyUserinfoActivity.class);
                intent.putExtra(IntentKey.ACTION, ModifyAction.MODIFY_EMAIL);
                intent.putExtra(IntentKey.BACK_TITLE, TITLE);
                if (Validator.isEffective(mUserinfo.getEmail())) {
                    intent.putExtra(IntentKey.MODIFY_CONTENT, mUserinfo.getEmail());
                }
                intent.putExtra(IntentKey.TITLE, "邮箱 ");
                startActivityForResult(intent, IntentForResultCODE.MODIFY_USERINFO_REQUESTCODE);
            }
        });
        //退出登录
        bnQuitLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(mContext)
                        .setTitle("温馨提示")
                        .setMessage("是否确定退出登录？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //改变样式
                                processUnLogin();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).show();
            }
        });
    }

    /**
     * 处理退出登录
     */
    private void processUnLogin() {
        //清除用户信息
        MyConfig.setUserId(mContext, null);
        MessageDispatcher.sendMessage(UserCenterFragment.getMyHandler(), MessageType.LOGIN_STATUS_CHANGED);
        T.shortToast(mContext, "已退出登录！");
        this.finish();
    }
    /**
     * 处理修改信息
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case IntentForResultCODE.MODIFY_NICKNAME_RESULTCODE:  //修改昵称
                if (data != null) {
                    String nickname = data.getStringExtra(IntentKey.MODIFY_CONTENT);
                    tvNickName.setText(nickname);
                    MessageDispatcher.sendMessage(UserCenterFragment.getMyHandler(), MessageType.LOGIN_STATUS_CHANGED);
                }
                break;
            case IntentForResultCODE.MODIFY_PHONE_RESULTCODE:     //修改手机号
                if (data != null) {
                    String phone = data.getStringExtra(IntentKey.MODIFY_CONTENT);
                    tvPhone.setText(phone);
                    MessageDispatcher.sendMessage(UserCenterFragment.getMyHandler(), MessageType.LOGIN_STATUS_CHANGED);
                }
                break;
            case IntentForResultCODE.MODIFY_EMAIL_RESULTCODE:   //修改邮箱
                if (data != null) {
                    String modifiedContent = data.getStringExtra(IntentKey.MODIFY_CONTENT);
                    tvEmail.setText(modifiedContent);
                    MessageDispatcher.sendMessage(UserCenterFragment.getMyHandler(), MessageType.LOGIN_STATUS_CHANGED);
                }
                break;
            case IntentForResultCODE.MODIFY_PASSWORD_RESULTCODE:   //修改密码
                T.shortToast(mContext, "修改密码成功，请重新登录");
                break;
            default:
                break;
            }
        }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final UserDetailActivity activity = (UserDetailActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (mProgressDialog != null) {
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成

                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
